#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Date:2022/07/18 16:34:13
'''
from sqlalchemy import and_
from Common.Utils import Utils

from db_logic.db_base import Repository
from models.client_models import EntityClientUser, EntityClientUser

#用户操作业务逻辑类
class BllClientUser(Repository):

    def __init__(self, entityType=EntityClientUser):
        super().__init__(entityType)

    def isJInZhiUser(self, userId, clientId):
        entity = self.findEntity(
            and_(EntityClientUser.user_id == userId, EntityClientUser.client_id == clientId))
        if(entity is None):
            return False
        else:
            return True
    
    def get_band_user_list(self, seach_user, client_id, page_param):
        filter_base = ""
        if seach_user:
            filter_base += f" real_name like '%{seach_user}%' "
        if filter_base:
            filter_base = f" where {filter_base} "
        sql_all = f"""
        SELECT a.user_id, a.real_name, a.role_name, a.avatar_url, 
	        CASE WHEN b.client_user_id is not null THEN 0 else 1 END status_type
	    from (select * from rms_user {filter_base}) as a LEFT JOIN(
		    select * from rms_client_user where client_id='{client_id}'
	    )as b on a.user_id=b.user_id
        """
        try:
            count_number = len(self.execute(sql_all).fetchall())
        except Exception:
            count_number = 0
        page_param.totalRecords=count_number
        page_sql = Utils.sql_paging_assemble(sql_all, page_param)
        return self.execute(page_sql).fetchall()
    
    def inster_user_client(self, user_id, client_id):
        try:
            if not self.findEntity(
                and_(
                    EntityClientUser.client_id == client_id,
                    EntityClientUser.user_id == user_id,
                    )
            ):
                self.insert(
                    EntityClientUser(
                        client_id=client_id,
                        user_id=user_id
                    )
                )
            return True
        except Exception:
            return False

    def del_user_ban_client(self, user_id, client_id):
        try:
            self.delete(
                and_(
                    EntityClientUser.user_id==user_id,
                    EntityClientUser.client_id== client_id
                )
            )
            return True
        except Exception:
            return False